<script setup lang="ts">
import { computed, ref } from 'vue';
import { useGraphStore } from '@/store/kg/graph';
import { useRouter } from 'vue-router';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
});

const emit = defineEmits(['update:visible']);

// 使用pinia store
const graphStore = useGraphStore();
// 使用router
const router = useRouter();

// 获取当前节点和节点属性
const currentNode = computed(() => graphStore.currentNode);
const nodeProperties = computed(() => graphStore.nodeProperties);
const loading = computed(() => graphStore.loading);

// 抽屉可见性双向绑定
const drawerVisible = computed({
  get: () => props.visible,
  set: (val) => {
    emit('update:visible', val);
  }
});

// 打开抽屉时的处理函数
const handleDrawerOpen = async () => {
  if (!currentNode.value) return;
  await graphStore.fetchNodeProperties(currentNode.value.id);
};

// 查看案例详情
const openCaseDetail = () => {
  if (currentNode.value?.id) {
    // 使用router.push在新标签页打开
    const routeUrl = `/#/kg/case/detail-view/${currentNode.value.id}`;
    window.open(routeUrl, '_blank');
  }
};

// 根据节点类型返回不同的标签类型
const getTagType = (nodeType: string | undefined): string => {
  if (!nodeType) return 'info';

  const typeMap: Record<string, string> = {
    'Course': 'warning',
    'Case': 'success',
    'Knowledge': 'primary',
    'Component': 'danger',
    'User': 'info',
    'File': 'info'
  };

  return typeMap[nodeType] || 'info';
};

// 节点属性中英文映射表
const propertyLabelMap: Record<string, Record<string, string>> = {
  // BaseNode通用属性
  base: {
    'nodeId': '节点ID',
    'name': '节点名称',
    'description': '节点描述',
    'color': '颜色',
    'size': '大小',
    'createTime': '创建时间',
    'updateTime': '更新时间',
    'createById': '创建人ID',
    'createByUsername': '创建人',
    'updateById': '更新人ID',
    'updateByUsername': '更新人'
  },
  // Knowledge节点特有属性
  Knowledge: {
    'level': '难度等级',
    'tags': '标签列表',
    'summary': '知识点摘要',
    'courseId': '所属课程ID'
  },
  // Case节点特有属性
  Case: {
    'cover': '案例封面',
    'type': '案例类型',
    'difficulty': '案例难度',
    'status': '案例状态',
    'auditMessage': '审核消息',
    'auditor': '审核人'
  },
  // Course节点特有属性
  Course: {
    'code': '课程编码',
    'credit': '课程学分',
    'status': '课程状态'
  },
  // Component节点特有属性
  Component: {
    'content': '组件内容'
  },
  // File节点特有属性
  File: {
    'fileId': '文件ID'
  }
};

// 根据节点类型和属性名获取对应的中文标签
const getPropertyLabel = (propertyKey: string): string => {
  // 先从通用属性中查找
  const baseLabel = propertyLabelMap.base[propertyKey];
  if (baseLabel) return baseLabel;
  
  // 再从特定节点类型的属性中查找
  if (currentNode.value?.type && propertyLabelMap[currentNode.value.type]) {
    const typeSpecificLabel = propertyLabelMap[currentNode.value.type][propertyKey];
    if (typeSpecificLabel) return typeSpecificLabel;
  }
  
  // 如果没找到匹配的中文标签，返回原属性名
  return propertyKey;
};

// 过滤不需要显示的属性
const filteredProperties = computed(() => {
  if (!nodeProperties.value) return {};
  
  const excludedKeys = ['labels', 'updateById', 'createById'];
  
  return Object.entries(nodeProperties.value)
    .filter(([key]) => !excludedKeys.includes(key))
    .reduce((obj, [key, value]) => {
      obj[key] = value;
      return obj;
    }, {} as Record<string, any>);
});

// 状态属性值格式化
const formatPropertyValue = (key: string, value: any): string => {
  // 处理案例状态
  if (key === 'status' && currentNode.value?.type === 'Case') {
    const caseStatusMap: Record<number, string> = {
      0: '草稿',
      1: '审核中',
      2: '已发布',
      3: '审核未通过',
      4: '已下架'
    };
    return caseStatusMap[value] || value;
  }
  
  // 处理知识点难度等级
  if (key === 'level' && currentNode.value?.type === 'Knowledge') {
    const levelMap: Record<number, string> = {
      1: '基础',
      2: '简单',
      3: '一般',
      4: '困难',
      5: '进阶'
    };
    return levelMap[value] || value;
  }
  
  // 处理日期时间格式化
  if ((key === 'createTime' || key === 'updateTime') && value) {
    try {
      const date = new Date(value);
      if (!isNaN(date.getTime())) {
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
      }
    } catch (e) {
      console.error('日期格式化错误:', e);
    }
  }
  
  // 处理数组类型的值（如标签列表）
  if (Array.isArray(value)) {
    return value.join(', ');
  }
  
  // 处理对象类型的值，转为JSON字符串
  if (typeof value === 'object' && value !== null) {
    return JSON.stringify(value);
  }
  
  return String(value);
};

// 添加控制文本展开的状态
const expandedItems = ref<Record<string, boolean>>({});

// 切换文本展开状态
const toggleExpand = (key: string) => {
  expandedItems.value[key] = !expandedItems.value[key];
};

// 检查文本是否应该显示展开按钮
const shouldShowExpand = (text: string): boolean => {
  return text.length > 100; // 如果文本长度超过100，显示展开按钮
};
</script>

<template>
  <el-drawer
    v-model="drawerVisible"
    title="节点详情"
    direction="rtl"
    size="30%"
    @open="handleDrawerOpen"
  >
    <div v-loading="loading" class="node-detail">
      <!-- 节点基本信息 -->
      <div class="node-header">
        <el-tag class="node-type-tag" :type="getTagType(currentNode?.type)">{{ currentNode?.type }}</el-tag>
        <h2 class="node-title">{{ currentNode?.label }}</h2>
      </div>

      <el-divider />

      <!-- 节点ID -->
      <div class="detail-item">
        <div class="id-row">
          <span class="label">ID：</span>
          <el-tag size="small" type="info">{{ currentNode?.id }}</el-tag>
        </div>
      </div>

      <!-- 节点属性列表 -->
      <div class="detail-item">
        <div class="properties-header">
          <span class="label">属性列表</span>
        </div>
        
        <el-empty v-if="Object.keys(filteredProperties || {}).length === 0" description="暂无属性数据" />
        
        <el-descriptions v-else :column="1" border class="property-descriptions">
          <el-descriptions-item
            v-for="(value, key) in filteredProperties"
            :key="key"
            :label="getPropertyLabel(key)"
            class="property-item"
          >
            <div 
              :class="[
                'property-value', 
                { 'text-ellipsis': !expandedItems[key], 'expanded': expandedItems[key] }
              ]"
            >
              {{ formatPropertyValue(key, value) }}
              <el-button 
                v-if="shouldShowExpand(String(formatPropertyValue(key, value)))"
                type="text" 
                size="small" 
                class="expand-btn"
                @click.stop="toggleExpand(key)"
              >
                {{ expandedItems[key] ? '收起' : '展开' }}
              </el-button>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 底部操作按钮 -->
      <div class="drawer-footer">
        <!-- 案例节点添加查看详情按钮 -->
        <el-button 
          v-if="currentNode?.type === 'Case'"
          type="primary" 
          @click="openCaseDetail"
        >
          查看案例详情
        </el-button>
        <el-button plain @click="drawerVisible = false">关闭</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<style scoped lang="scss">
.node-detail {
  padding: 16px;
  display: flex;
  flex-direction: column;
  height: 100%;

  .node-header {
    margin-bottom: 16px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;

    .node-type-tag {
      font-size: 0.8rem;
    }

    .node-title {
      font-size: 1.5rem;
      font-weight: bold;
      margin: 8px 0;
      color: #303133;
    }
  }

  .detail-item {
    margin-bottom: 24px;

    .label {
      font-weight: bold;
      color: #333;
      margin-right: 8px;
      display: block;
      margin-bottom: 12px;
      font-size: 1rem;
    }
  }

  .id-row {
    display: flex;
    align-items: center;
    gap: 8px;

    .label {
      margin-bottom: 0;
    }
  }

  .properties-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .property-descriptions {
    width: 100%;
    
    :deep(table) {
      table-layout: fixed;
      width: 100%;
    }
  }

  .property-item {
    :deep(.el-descriptions__cell) {
      width: 25%;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    :deep(.el-descriptions__content) {
      width: 75%;
      max-width: 75%;
      table-layout: fixed;
    }
  }
  
  .property-value {
    color: #666;
    word-break: break-all;
    padding: 4px 0;
    max-height: 300px;
    overflow: hidden;
    transition: max-height 0.3s;
    position: relative;
    
    &.expanded {
      max-height: none;
      overflow: visible;
    }
    
    .expand-btn {
      position: absolute;
      right: 0;
      bottom: 0;
      background: linear-gradient(to right, transparent, #fff 30%);
      padding-left: 20px;
      
      .expanded & {
        position: static;
        display: block;
        background: none;
        margin-top: 5px;
        padding-left: 0;
      }
    }
  }

  .text-ellipsis {
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .drawer-footer {
    margin-top: auto;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding: 16px 0;
  }
}
</style>
